<?php

require_once dirname(__FILE__) . '/../../lib/Slim/Slim.php';
//require_once 'Slim.php';
require_once 'utils.php';
require_once 'error.php';

class Response{
	const CODE_SUCCESS = 0;
	const CODE_FATAL_ERROR = 1;
	const CODE_ERROR_DB_INSERT_FAILED = 2;
	const CODE_ERROR_DB_UPDATE_FAILED = 3;
	const CODE_ERROR_DB_SELECT_FAILED = 4;

	/**
	 * Composes and sends the response message.
	 */
	public static function finalizeMessage($code, $message){
		self::finalizeResponse($code, array(
				'result' => $code,
				'message' => $message
			)
		);
	}

	/**
	 * Composes and sends a new message notifying the error.
	 * Moreover it also reports the error to the database.
	 * @param code The error code associated to this response
	 * @param e An error description.
	 */
	public static function finalizeError($code, Error $e){
		$e->report();
		self::finalizeResponse($code, array(
			'result' => $code,
			'message'=> $e->toString()
			)
		);
	}

	/**
	 * Composes and sends the response message.
	 * The values are passed in an associative array which will be converted
	 * and sent as JSON.
	 */
	public static function finalizeResponse($code, $values){
		global $app;
		$response = $app->response();	
		$response['Content-Type'] = 'application/json';

		$json = json_encode($values, JSON_FORCE_OBJECT);
		if(!$json){
			$response->status(500);
			$result = '{'
				.'"result" : ' . self::CODE_FATAL_ERROR
				.'"message" : "Fatal error while encoding ' . $values . ' in json"'
				.'}';
			$response->body($result);
		}

		if($code != self::CODE_SUCCESS)
			$response->status(400);

		$response->body($json);
	}
}

?>
